Function Wait-DeploymentStabilized
{
	[CmdletBinding()]
	Param
    (
        [Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
        [string]$StorageAccountName, 

        [Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
        [string]$StorageAccountKey, 

        [Parameter(Mandatory=$True, ValueFromPipeline=$True, ValueFromPipelineByPropertyName=$True)]
        [string]$DeploymentId
    )

	Add-Type -Assembly System.Web 
	$serializer = New-Object System.Web.Script.Serialization.JavaScriptSerializer

    $state = "Configuring"
    $continue = $true
    $since = 0
    do
    {
        Start-Sleep -Seconds 10
        $logs = Get-DeployerLogs -StorageAccountName $StorageAccountName -StorageAccountKey $StorageAccountKey -DeploymentId $DeploymentId -Since $since
        foreach ($log in $logs)
        {
            if ($log -ne $null)
            {
                $firstIndex = $log.Message.IndexOf("{")
                $lastIndex = $log.Message.LastIndexOf("}")

                if ($firstIndex -gt 0 -and $lastIndex -gt 0)
                {
                    $obj = $serializer.DeserializeObject($log.Message.Substring($firstIndex, $lastIndex - $firstIndex + 1))

                    Write-Host "Progress $($obj["Progress"]), Message: $($obj["Message"]), State: $($obj["State"])"

                    $state = $obj["State"]
                }
                else
                {
                    $state = "Failed"
                }

                $since = $log.EventTickCount
            }
        }

        if ($state -eq "Finished") { $continue = $false }
        if ($state -eq "Cancelled") { $continue = $false }
    }
    while($continue)

    return $state;
}